<?php


namespace Tbf\Component\Http;


use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SymfonyHttpFunction {
    /**
     * 添加跨站头
     * @param Request $request
     * @param Response $response
     */
    public static function addCrossDomainHeader(Request $request,Response $response){
        if ($request->headers->has('Origin')){
            $origin = $request->headers->get('Origin');
        }else{
            $origin = '*';
        }
        $response->headers->set('Access-Control-Allow-Origin',$origin);
        if ($request->headers->has('Access-Control-Request-Method')){
            $response->headers->set('Access-Control-Allow-Methods','POST, GET, HEAD');
        }
        if ($request->headers->has('Access-Control-Request-Headers')){
            $response->headers->set('Access-Control-Allow-Headers',$request->headers->get('Access-Control-Request-Headers'));
        }
        if ($request->getMethod()==='OPTIONS'){
            $response->headers->set('Access-Control-Max-Age','1728000');
        }
    }

    /**
     * 添加跨站cookie头
     * 可以在另一个站上 发送请求, php在本站设置cookie
     * @param Request $request
     * @param Response $response
     */
    public static function addCrossDomainCookieHeader(Request $request,Response $response){
        self::addCrossDomainHeader($request,$response);
        $response->headers->set('Access-Control-Allow-Credentials','true');
    }

    /**
     * @param Response $resp
     * @param $mime_type
     * @param $file_name
     */
    public static function addAttachmentHeader(Response $resp,$mime_type=null,$file_name=null){
        if ($mime_type!==null){
            $resp->headers->set('Content-type',$mime_type);
        }
        if ($file_name!==null){
            // some characters in filename will break browser...
            // see: http://stackoverflow.com/a/216777/1586797
            // see: http://greenbytes.de/tech/tc2231/#attrfc2047quoted
            // to work around: use a URL that contains the filename you want.
            if (!preg_match('{^[a-zA-Z0-9.\-_]+$}',$file_name)){
                throw new \Exception('you can not set a filename in attachment with some characters not in [a-zA-Z0-9.-_]');
            }
            $resp->headers->set('Content-Disposition','attachment;filename="'.$file_name.'"');
        }else{
            $resp->headers->set('Content-Disposition','attachment');
        }
        $resp->headers->set('Cache-Control','max-age=0');
    }
}